package Java工具收集;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import lombok.Data;


public class EmailUtils {

     public static void main(String[] args) throws Exception {

        // 收件人电子邮箱
        String[] to = {"864443572@qq.com"};
        // 发件人电子邮箱
//        String from = "747491914@qq.com";

        // 指定发送邮件的主机为 smtp.qq.com
//        String host = "smtp.qq.com";  	//QQ 邮件服务器
        String mailServerAddress = "mail.ewell.cc";  	//QQ 邮件服务器

        String senderEmailAccount = "xiaoronghui@ewell.cc";	//发件人邮件用户名、授权码

        String senderLicenseCodeOrPassword = "ewell123";

        String emailTitle = "整点数据3"; 

        String emailContent = "在马勒戈壁的荒漠上有一群草泥马ddd.....";

//        sendTextMessage(senderEmailAccount, senderLicenseCode, mailServerAddress, emailTitle, emailContent, Arrays.asList(to));
        
        sendTextAttachmentMessage(senderEmailAccount, senderLicenseCodeOrPassword, mailServerAddress, emailTitle, emailContent, Arrays.asList(to), Arrays.asList("D:/图片/1.jpg"));
        
        //支持文本发送
        //String text = "This is actual message";
        //sendTextMessage(username,password,to,from,host,subject,text);

        //支持附件发送
//        List<String> paths = new ArrayList<>();
//        paths.add("/jxl_test.xlsx");
//        paths.add("/merge.xls");
//        sendAttachmentMessage(username,password,to,from,host,subject,text,paths);
        

    }
     
     /**
	 * @function 群发文本邮件
	 * @param senderEmailAccount 发送方邮件账号
	 * @param senderLicenseCodeOrPassword 发送方邮件授权码或密码
	 * @param mailServerAddress 发送方邮件服务器地址
	 * @param emailTitle 邮件标题
	 * @param emailContent 邮件内容
	 * @param receiverEmailAccountList 接收方邮件账户列表
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
   public static void sendTextMessage(String senderEmailAccount ,  String senderLicenseCodeOrPassword , String mailServerAddress , String emailTitle , String emailContent , List<String> receiverEmailAccountList ) throws Exception{

        // 获取系统属性
        Properties properties = new Properties();

        //设置邮件服务器
        properties.setProperty("mail.smtp.host", mailServerAddress);

        properties.put("mail.smtp.auth", "true");

        //根据发送方提供的账号和授权码连接邮件服务器获取会话session
        Session session = Session.getDefaultInstance(properties , new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmailAccount , senderLicenseCodeOrPassword);
            }
        });

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(senderEmailAccount));

        InternetAddress[] sendTo = new InternetAddress[receiverEmailAccountList.size()];
        
        for(int i = 0 ; i < receiverEmailAccountList.size() ; i ++) {
        	String receiverEmailAccount = receiverEmailAccountList.get(i);
        	sendTo[i] = new InternetAddress(receiverEmailAccount);
        }
        
        message.setRecipients(MimeMessage.RecipientType.TO , sendTo);
        message.setSubject(emailTitle);
        message.setText(emailContent);

        Transport.send(message);
        
        System.out.println("Sent message successfully");
            
    }
   
   /**
    * @function 群发文本邮件
    * @param emailInfo 邮件信息
    * @author 肖荣辉
    * @date 2021年3月24日
   */
    public static void sendTextMessage(EmailInfo emailInfo) throws Exception{
    	sendTextMessage(emailInfo.getSenderEmailAccount() ,emailInfo.getSenderLicenseCodeOrPassword() , emailInfo.getMailServerAddress() , emailInfo.getEmailTitle() , emailInfo.getEmailContent() , emailInfo.getReceiverEmailAccountList());
     }
   
   /**
	 * @function 群发HTML文本邮件
	 * @param senderEmailAccount 发送方邮件账号
	 * @param senderLicenseCodeOrPassword 发送方邮件授权码或密码
	 * @param mailServerAddress 发送方邮件服务器地址
	 * @param emailTitle 邮件标题
	 * @param emailContent 邮件内容
	 * @param receiverEmailAccountList 接收方邮件账户列表
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
	 public static void sendHTMLMessage(String senderEmailAccount ,  String senderLicenseCodeOrPassword , String mailServerAddress , String emailTitle , String emailContent , List<String> receiverEmailAccountList )  throws Exception{
	
	      Properties properties = new Properties();
	
	      //设置邮件服务器
	      properties.setProperty("mail.smtp.host", mailServerAddress);
	
	      properties.put("mail.smtp.auth", "true");
	
	      //根据发送方提供的账号和授权码连接邮件服务器获取会话session
	      Session session = Session.getDefaultInstance(properties , new Authenticator(){
	          public PasswordAuthentication getPasswordAuthentication() {
	              return new PasswordAuthentication(senderEmailAccount , senderLicenseCodeOrPassword);
	          }
	      });
	
	
	      MimeMessage message = new MimeMessage(session);
	
	      message.setFrom(new InternetAddress(senderEmailAccount));
	
	      InternetAddress[] sendTo = new InternetAddress[receiverEmailAccountList.size()];
	      
	      for(int i = 0 ; i < receiverEmailAccountList.size() ; i ++) {
	      	String receiverEmailAccount = receiverEmailAccountList.get(i);
	      	sendTo[i] = new InternetAddress(receiverEmailAccount);
	      }
	      
	      message.setRecipients(MimeMessage.RecipientType.TO , sendTo);
	      message.setSubject(emailTitle);
	      message.setContent(emailContent ,"text/html;charset=utf8");
	
	      Transport.send(message);
	      
	      System.out.println("Sent message successfully");
	
	  }
	 
	/**
	 * @function 群发HTML文本邮件
	 * @param emailInfo 邮件信息
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
	public static void sendHTMLMessage(EmailInfo emailInfo)  throws Exception{
		sendHTMLMessage(emailInfo.getSenderEmailAccount() ,emailInfo.getSenderLicenseCodeOrPassword() , emailInfo.getMailServerAddress() , emailInfo.getEmailTitle() , emailInfo.getEmailContent() , emailInfo.getReceiverEmailAccountList());
	}
	
	/**
	 * @function 群发带附件的文本邮件
	 * @param senderEmailAccount 发送方邮件账号
	 * @param senderLicenseCodeOrPassword 发送方邮件授权码或密码
	 * @param mailServerAddress 发送方邮件服务器地址
	 * @param emailTitle 邮件标题
	 * @param emailContent 邮件内容
	 * @param receiverEmailAccountList 接收方邮件账户列表
	 * @param attachmentFilePathList 附件文件地址列表
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
    public static void sendTextAttachmentMessage( String senderEmailAccount ,  String senderLicenseCodeOrPassword ,  String mailServerAddress , String emailTitle , String emailContent , List<String> receiverEmailAccountList ,  List<String> attachmentFilePathList) throws Exception{

        Properties properties = new Properties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", mailServerAddress);
        
        properties.put("mail.smtp.auth", "true");

        //根据发送方提供的账号和授权码连接邮件服务器获取会话session
        Session session = Session.getDefaultInstance(properties , new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmailAccount, senderLicenseCodeOrPassword);
            }
        });

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(senderEmailAccount));

        InternetAddress[] sendTo = new InternetAddress[receiverEmailAccountList.size()];
        
        for(int i = 0 ; i < receiverEmailAccountList.size() ; i ++) {
        	String receiverEmailAccount = receiverEmailAccountList.get(i);
        	sendTo[i] = new InternetAddress(receiverEmailAccount);
        }
        
        message.setRecipients(MimeMessage.RecipientType.TO , sendTo);
        
        //设置标题
        message.setSubject(emailTitle);

        // 设置正文
        BodyPart bp = new MimeBodyPart();
        Multipart mp = new MimeMultipart();
        bp.setText(emailContent);
        mp.addBodyPart(bp);

        // 设置附件
        for(int i = 0 ; attachmentFilePathList != null && i < attachmentFilePathList.size() ; i++) {
            bp = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attachmentFilePathList.get(i));
            bp.setDataHandler(new DataHandler(fds));
            bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
            mp.addBodyPart(bp);
        }
        
        message.setContent(mp);
        message.saveChanges();
        Transport.send(message);
    }
    
    /**
     * @function 群发带附件的文本邮件
     * @param emailInfo 邮件信息
     * @author 肖荣辉
     * @date 2021年3月24日
    */
    public static void sendTextAttachmentMessage(EmailInfo emailInfo)  throws Exception{
    	sendTextAttachmentMessage(emailInfo.getSenderEmailAccount() ,emailInfo.getSenderLicenseCodeOrPassword() , emailInfo.getMailServerAddress() , emailInfo.getEmailTitle() , emailInfo.getEmailContent() , emailInfo.getReceiverEmailAccountList() , emailInfo.getAttachmentFilePathList());
    }

 	/**
	 * @function 群发带附件的HTML文本邮件
	 * @param senderEmailAccount 发送方邮件账号
	 * @param senderLicenseCodeOrPassword 发送方邮件授权码或密码
	 * @param mailServerAddress 发送方邮件服务器地址
	 * @param emailTitle 邮件标题
	 * @param emailContent 邮件内容
	 * @param receiverEmailAccountList 接收方邮件账户列表
	 * @param attachmentFilePathList 附件文件地址列表
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
    public static void sendHTMLAttachmentMessage( String senderEmailAccount ,  String senderLicenseCodeOrPassword ,  String mailServerAddress , String emailTitle , String emailContent , List<String> receiverEmailAccountList ,  List<String> attachmentFilePathList) throws Exception{

        Properties properties = new Properties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", mailServerAddress);
        
        properties.put("mail.smtp.auth", "true");

        //根据发送方提供的账号和授权码连接邮件服务器获取会话session
        Session session = Session.getDefaultInstance(properties , new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmailAccount, senderLicenseCodeOrPassword);
            }
        });

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(senderEmailAccount));

        InternetAddress[] sendTo = new InternetAddress[receiverEmailAccountList.size()];
        
        for(int i = 0 ; i < receiverEmailAccountList.size() ; i ++) {
        	String receiverEmailAccount = receiverEmailAccountList.get(i);
        	sendTo[i] = new InternetAddress(receiverEmailAccount);
        }
        
        message.setRecipients(MimeMessage.RecipientType.TO , sendTo);
        
        //设置标题
        message.setSubject(emailTitle);

        // 设置正文
        BodyPart bp = new MimeBodyPart();
        Multipart mp = new MimeMultipart();
        bp.setContent(emailContent, "text/html;charset=utf-8");
        mp.addBodyPart(bp);

        // 设置附件
        for(int i = 0 ; attachmentFilePathList != null && i < attachmentFilePathList.size() ; i++) {
            bp = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attachmentFilePathList.get(i));
            bp.setDataHandler(new DataHandler(fds));
            bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
            mp.addBodyPart(bp);
        }
        
        message.setContent(mp);
        message.saveChanges();
        Transport.send(message);
    }
    
    /**
     * @function 群发带附件的HTML文本邮件
     * @param emailInfo 邮件信息
     * @author 肖荣辉
     * @date 2021年3月24日
    */
    public static void sendHTMLAttachmentMessage(EmailInfo emailInfo)  throws Exception{
    	sendHTMLAttachmentMessage(emailInfo.getSenderEmailAccount() ,emailInfo.getSenderLicenseCodeOrPassword() , emailInfo.getMailServerAddress() , emailInfo.getEmailTitle() , emailInfo.getEmailContent() , emailInfo.getReceiverEmailAccountList() , emailInfo.getAttachmentFilePathList());
    }
    
    /**
	 * @function 邮件信息类
	 * @author 肖荣辉
	 * @date 2021年3月24日
	*/
    @Data
    public static class EmailInfo{
    	
    	//发送方邮件账号
    	private String senderEmailAccount; 
    	
    	//发送方邮件授权码或密码
    	private String senderLicenseCodeOrPassword; 
    	
    	//发送方邮件服务器地址
    	private String mailServerAddress;
    	
    	//邮件标题
    	private String emailTitle;
    	
    	//邮件内容
    	private String emailContent;
    	
    	//接收方邮件账户列表
    	private List<String> receiverEmailAccountList;
    	
    	//附件文件地址列表
    	private List<String> attachmentFilePathList;

		public EmailInfo(String senderEmailAccount, String senderLicenseCodeOrPassword, String mailServerAddress,
				String emailTitle, String emailContent, List<String> receiverEmailAccountList,
				List<String> attachmentFilePathList) {
			super();
			this.senderEmailAccount = senderEmailAccount;
			this.senderLicenseCodeOrPassword = senderLicenseCodeOrPassword;
			this.mailServerAddress = mailServerAddress;
			this.emailTitle = emailTitle;
			this.emailContent = emailContent;
			this.receiverEmailAccountList = receiverEmailAccountList;
			this.attachmentFilePathList = attachmentFilePathList;
		}
		
		public EmailInfo(String senderEmailAccount, String senderLicenseCodeOrPassword, String mailServerAddress,
				String emailTitle, String emailContent , String receiverEmailAccount ,
				List<String> attachmentFilePathList) {
			super();
			this.senderEmailAccount = senderEmailAccount;
			this.senderLicenseCodeOrPassword = senderLicenseCodeOrPassword;
			this.mailServerAddress = mailServerAddress;
			this.emailTitle = emailTitle;
			this.emailContent = emailContent;
			this.receiverEmailAccountList = Arrays.asList(receiverEmailAccount);
			this.attachmentFilePathList = attachmentFilePathList;
		}

		public EmailInfo() {
			super();
		}
    	
    }

}
